# encoding: utf-8
"""
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    created by lei.chang on '18/12/2024'
    comment: 扣子平台相关
"""
import asyncio

import aiohttp
import ujson

from config import Config
from project.core.exception import BizError
from project.lib.common import logger


class Coze:

    headers = {
        'Authorization': f'Bearer {Config.COZE_OPTIONS["personal_token"]}',
        'Content-Type': 'application/json'
    }

    @classmethod
    async def run_workflow(cls, workflow_id):
        """ 执行工作流
        :return:
        """
        url = 'https://api.coze.cn/v1/workflow/run'

        async with aiohttp.ClientSession() as session:
            async with session.post('https://api.coze.cn/v1/workflow/run', headers=cls.headers, json={'workflow_id': workflow_id}) as resp:
                if resp.status != 200:
                    error = f'扣子执行工作流失败 url: {url} status: {resp.status} content: {(await resp.content.read())}'
                    logger.error(message=error)
                    raise BizError(message=error)

                result = await resp.json()

                ret_data = ujson.loads(result['data'])
                if ret_data.get('code', 0) != 0:
                    error = f'扣子执行工作流失败 url: {url} code: {ret_data.get("code", 0)} msg: {ret_data.get("msg", "")}'
                    logger.error(message=error)
                    raise BizError(message=error)

        return ujson.loads(result['data'])

if __name__ == "__main__":

    result = asyncio.run(Coze.run_workflow('7449952731638890537'))
    print(result)
